/**
 * 易驰护运 - ApplyMessageCard
 * http://menger.me
 * 接单信息卡片
 * @桓桓
 */

'use strict';

import React from 'react'
import {
    Text,
    View,
    Image,
    Keyboard,
    TextInput,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
} from 'react-native'
import {
    IconFont,
} from '../../../components'
import {Predefine} from '../../../config/predefine'

export default class ApplyMessageCard extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            item: '',
            dataSource: [],
            weight: '', // 接单吨数
            price: '', // 报价单价

            carrier_receipt_weight: 0, // 承接总吨数
            carrier_vehicle_num: 0, // 承运用车数量
            carrier_vehicle_id: [],
            dateArray: [],
            timeArray: [],

            year: '',
            month: '',
            day: '',
            showAll: false,
        };
    }

    componentWillUpdate() { // 这样进入页面最后一次把数据刷新进车辆列表就能把值拿出来了
        this.setDataSource()
    }

    setDataSource = () => {
        let {item, carList} = this.props;
        this.setState({
            item: item,
            dataSource: carList,
        })
    }

    // 选中或取消选中车辆
    changeLeisure = (item, index) => {
        let {getApplyMessageCardVal} = this.props;
        let {dataSource, carrier_receipt_weight, carrier_vehicle_num, carrier_vehicle_id} = this.state;
        let newItem = dataSource[index]; // 声明一个假的替代视图数据
        let newDataSource = dataSource.slice(); // 声明一个替代的选车效果视图
        let _carrier_receipt_weight = carrier_receipt_weight, _carrier_vehicle_num = carrier_vehicle_num// 声明一个替代的总吨数/总数量
        let _carrier_vehicle_id = carrier_vehicle_id.slice();
        if (item.leisure == true) { // 已选中
            newItem.leisure = false
            _carrier_receipt_weight = parseInt(carrier_receipt_weight) - parseInt(item.vehicle_weight) // 后端返回的可能是字符串，会变成字符串的拼接。
            _carrier_vehicle_num = carrier_vehicle_num - 1
            if (_carrier_vehicle_id.indexOf(item.id) > -1) {
                _carrier_vehicle_id.splice(_carrier_vehicle_id.indexOf(item.id), 1)
            }
        } else { // 未选中
            newItem.leisure = true
            _carrier_receipt_weight = parseInt(carrier_receipt_weight) + parseInt(item.vehicle_weight)
            _carrier_vehicle_num = carrier_vehicle_num + 1
            _carrier_vehicle_id.push(item.id)
        }
        newDataSource[index] = newItem; // 最终能用的显示效果
        this.setState({
            dataSource: newDataSource,
            carrier_receipt_weight: _carrier_receipt_weight,
            carrier_vehicle_num: _carrier_vehicle_num,
            carrier_vehicle_id: _carrier_vehicle_id,
        }, () => {
            let data = {
                carTotalWeight: _carrier_receipt_weight, // 车辆总重量
                carTotalNum: _carrier_vehicle_num, // 车辆总数量
                carTotalId: _carrier_vehicle_id, // 所选车辆的id，逗号分割的字符串。
            }
            getApplyMessageCardVal(data, 1) // 把数据传给上个页面
        }); // 把新的选中的车放进去
    }

    choiceDate = (carsIndex) => {
        let {choiceDate} = this.props;
        let {dateArray, dataSource} = this.state;
        let arr = dateArray.slice()
        let params = {
            onPress: (value) => {
                let date = value.year+'-'+value.month+'-'+value.day;
                if (arr.length == 0) {
                    dataSource.map((item, index) => {
                        if ( carsIndex == index ) {
                            arr.push(date)
                        } else {
                            arr.push('')
                        }
                    })
                } else {
                    dataSource.map((item, index) => {
                        if ( carsIndex == index ) {
                            arr.splice(index, 1, date)
                        }
                    })
                }
                this.setState({dateArray: arr}, () => choiceDate && choiceDate(arr))
            },
            option: {
                panGestureEnabled: false,
            }
        }
        ActionManager.showWheelDate(params);
    }

    choiceTime = (carsIndex) => {
        let {choiceTime} = this.props;
        let {timeArray, dataSource} = this.state;
        let arr = timeArray.slice()
        let params = {
            onPress: (value) => { 
                if (arr.length == 0) {
                    dataSource.map((item, index) => {
                        if ( carsIndex == index ) {
                            arr.push(value.hour+':'+value.minute)
                        } else {
                            arr.push('')
                        }
                    })
                } else {
                    dataSource.map((item, index) => {
                        if ( carsIndex == index ) {
                            arr.splice(index, 1, value.hour+':'+value.minute)
                        }
                    })
                }
                this.setState({timeArray: arr}, () => choiceTime && choiceTime(arr))
            },
            option: {
                panGestureEnabled: false,
            }
        }
        ActionManager.showTimeContent(params);
    }

    // 时间选择
    showActionTimePicker = () => {
        Keyboard.dismiss();
        let params = {
            onPress: (value) => {
                this.setState({
                    year: value.year,
                    month: value.month,
                    day: value.day,
                })
            },
            option: {
                panGestureEnabled: false,
            }
        }
        ActionManager.showWheelDate(params);
    };

    cardListView = (state) => {
        let {dataSource, showAll, dateArray, timeArray} = state;
        if (dataSource.length == 0) {
            return (
                <View style={styles.noCar}>
                    <Text style={styles.noCarText} numberOfLines={1}>*暂无符合要求的车辆</Text>
                </View>
            )
        }
        //承运商选择接单车辆的时候默认显示三个车，点击更多车辆，展示所有满足条件的车辆，可以选择
        let contain = dataSource.map((item, index) => {
            if (index > 2 && !showAll) {
                return null;
            } else {
                this.setState({showAll: true})
            }
            return (
                <TouchableOpacity
                    key={index}
                    style={[styles.carCard, item.leisure == true && {backgroundColor: '#CAF2F7'}]}
                    onPress={() => this.changeLeisure(item, index)}
                >
                    <View style={styles.carCardHeader}>
                        <View style={styles.carCardHeaderBall}/>
                        <Text style={styles.carCardHeaderText}>
                            {item.status == 0 && '审核中'}
                            {item.status == 1 && '闲置中'}
                            {item.status == 2 && '运营中'}
                        </Text>
                    </View>
                    <View style={styles.carCardLine}>
                        <Text style={styles.carCardLineText} numberOfLines={1}>车牌号：{item.vehicle_number}</Text>
                        <Text style={styles.carCardLineText} numberOfLines={1}>司机姓名：{item.driver_name}</Text>
                    </View>
                    <View style={styles.carCardLine}>
                        <Text style={styles.carCardLineText} numberOfLines={1}>车辆类型：{item.vehicle_type_text}</Text>
                        <Text style={styles.carCardLineText} numberOfLines={1}>车辆载重：{item.vehicle_weight}吨</Text>
                    </View>
                    <View style={styles.carCardTimeLine}>
                        <Text style={styles.carCardLineTitle}>预计到达时间：</Text>
                        <View style={styles.carCardLine}>
                            <TouchableOpacity style={styles.carCardLineInputBox} onPress={() => this.choiceDate(index)}>
                                <Text style={styles.carCardLineInput} numberOfLines={1}>{dateArray[index] && dateArray[index] || '请点击选择日期'}</Text>
                                <IconFont.Fontisto name={'date'} size={14} color={DominantColor}/>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.carCardLineInputBox} onPress={() => this.choiceTime(index)}>
                                <Text style={styles.carCardLineInput} numberOfLines={1}>{timeArray[index] && timeArray[index] || '请点击选择时间'}</Text>
                                <IconFont.MaterialIcons name={'access-time'} size={14} color={DominantColor}/>
                            </TouchableOpacity>    
                        </View>
                    </View>
                    {
                        item.leisure == true &&
                        <ImageView
                            resizeMode={'contain'}
                            style={styles.carCardImg}
                            source={Images.icon_choice_car}
                        />
                    }
                </TouchableOpacity>
            );
        })
        return (
            <View style={styles.carView}>
                <View style={[Predefine.RCB, styles.carViewHeader]}>
                    <Text style={styles.carViewHeaderText}>接单车辆<Text style={{color: '#E71426'}}>*</Text>:</Text>
                </View>
                {contain}
            </View>
        )
    }

    render() {
        let {payType, getApplyMessageCardVal} = this.props; // 父页面传数据
        let {item, dataSource, weight, price, carrier_receipt_weight, carrier_vehicle_num, showAll} = this.state;
        return (
            <View style={styles.card}>
                <View style={styles.cardHeader}>
                    <View style={styles.cardHeaderBall}><View style={styles.cardHeaderBallCenter}/></View>
                    <Text style={styles.cardHeaderText} numberOfLines={1}>详细地址</Text>
                </View>
                <View style={styles.carForm}>
                    <Text style={styles.carFromTitle}>接单吨数<Text style={{color: '#E71426'}}>*</Text>：</Text>
                    <Text style={[styles.carFromText, {color: '#333'}]}
                          numberOfLines={1}>{carrier_receipt_weight}</Text>
                    <Text style={styles.carFromText}>吨</Text>
                </View>
                <View style={styles.carForm}>
                    <Text style={styles.carFromText}>货源剩余未承运吨数：<Text style={{color: '#FF651D'}}>{item.remanent_weight}</Text>吨</Text>
                </View>
                {
                    payType == '竞价发布' &&
                    <View style={styles.carForm}>
                        <Text style={styles.carFromTitle}>接单报价<Text style={{color: '#E71426'}}>*</Text>：</Text>
                        <TextInput
                            defaultValue={price}
                            style={styles.carFromInput}
                            placeholder={'请输入'}
                            placeholderTextColor={'#999'}
                            keyboardType={'phone-pad'}
                            onChangeText={(text) => {
                                let newText = text.replace(/[^\d]+/, ''); // 只要数字
                                this.setState({
                                    price: newText
                                }, () => getApplyMessageCardVal && getApplyMessageCardVal(newText, 3))
                            }}
                        />
                        <Text style={styles.carFromText}>/吨</Text>
                    </View>
                }
                {this.cardListView(this.state)}
                <View style={styles.cardLine}>
                    <Text style={styles.cardLineLeft}>可承接总吨数：</Text>
                    <Text style={styles.cardLineRight} numberOfLines={1}><Text style={{color: '#FF651D'}}>{carrier_receipt_weight}</Text>吨</Text>
                </View>
                <View style={styles.cardLine}>
                    <Text style={styles.cardLineLeft}>承接车辆数：</Text>
                    <Text style={styles.cardLineRight} numberOfLines={1}>{carrier_vehicle_num}辆</Text>
                </View>
            </View>
        );
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    card: {
        marginBottom: 10,
        backgroundColor: '#fefefe',
        paddingHorizontal: 15,
    },
    cardHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 40,
    },
    cardHeaderBall: {
        width: 12,
        height: 12,
        borderRadius: 6,
        backgroundColor: DominantColor,
        marginRight: 6,
        alignItems: 'center',
        justifyContent: 'center',
    },
    cardHeaderBallCenter: {
        height: 6,
        width: 6,
        borderRadius: 3,
        backgroundColor: '#fff',
    },
    cardHeaderText: {
        color: '#333',
        fontSize: 15,
        fontWeight: 'bold',
    },
    // 顶部form
    carForm: {
        height: 30,
        flexDirection: 'row',
        alignItems: 'center',
    },
    carFromTitle: {
        color: '#333',
        fontSize: 14,
    },
    carFromInput: {
        borderWidth: Predefine.minPixel,
        borderColor: '#e1e1e1',
        borderRadius: 5,
        height: 26,
        width: Predefine.screenWidth - 200,
        paddingVertical: 0,
        paddingHorizontal: 10,
        fontSize: 14,
        marginRight: 6,
    },
    carFromText: {
        color: '#999',
        fontSize: 14,
    },
    // 选车的卡片
    carView: {
        marginTop: 10,
        borderTopWidth: Predefine.minPixel,
        borderTopColor: '#e1e1e1',
    },
    carViewHeader: {
        height: 40,
    },
    carViewHeaderText: {
        fontSize: 14,
    },

    carCard: {
        borderWidth: Predefine.minPixel,
        borderColor: '#e1e1e1',
        borderRadius: 5,
        marginBottom: 10,
        paddingHorizontal: 10,
        paddingVertical: 5,
    },
    carCardHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 25,
    },
    carCardHeaderBall: {
        width: 10,
        height: 10,
        borderRadius: 5,
        marginRight: 6,
        backgroundColor: DominantColor,
    },
    carCardHeaderText: {
        color: DominantColor,
        fontSize: 14,
    },
    carCardLine: {
        height: 30,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    carCardLineText: {
        flex: 1,
        fontSize: 14,
        color: '#333',
    },
    carCardLineTitle: {
        lineHeight: 30,
        fontSize: 14,
        color: '#333',
    },
    carCardLineInputBox: {
        height: 26,
        borderWidth: 1,
        borderColor: DominantColor,
        borderRadius: 5,
        marginHorizontal: 5,
        flex: 1,
        paddingHorizontal: 5,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    carCardLineInput: {},
    carCardImg: {
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: 28,
        height: 30,
    },

    cardLine: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 30,
    },
    cardLineLeft: {
        color: '#333',
        fontSize: 14,
    },
    cardLineRight: {
        color: '#666',
        fontSize: 14,
    },

    noCar: {
        paddingVertical: 15,
    },
    noCarText: {
        fontSize: 15,
        color: DominantColor,
    },
});